<template>
  <div class="register-content">
    <back-bar title="注册" @toBack="toBack" />
    <div class="registerInfo-box">
      <div>
        <van-field
          name="uploader"
          label="上传头像"
          center
          colon
          input-align="right"
          class="headimg-box"
          :max-size="500 * 1024" 
          @oversize="onOversize"
        >
          <template #input>
            <van-uploader
              v-model="uploader"
              :after-read="afterRead"
              :max-size="500 * 1024"
              @oversize="onOversize"
              :max-count="1"
              class="headimg-box"
              multiple
            />
          </template>
        </van-field>
        <van-field
          v-model="regsisterIfo.userName"
          label="用户名"
          maxlength="10"
          placeholder="请输入用户名"
          clearable
          colon
          clickable
          autofocus
          required
        >
          <!-- <template #button>
            <van-uploader :after-read="afterRead">
              <van-button size="small" icon="plus" type="primary" class="filebtn">上传头像</van-button>
          </van-uploader>
          </template>-->
        </van-field>
        <van-field
          v-model="regsisterIfo.nickName"
          label="昵称"
          maxlength="8"
          placeholder="请输入昵称"
          clearable
          colon
          clickable
          autofocus
        />
        <van-field
          v-model="regsisterIfo.password"
          type="password"
          label="密码"
          placeholder="请输入密码"
          clearable
          colon
          clickable
          required
        />
        <van-field
          v-model="checkPassword"
          type="password"
          label="确认密码"
          placeholder="请确认密码"
          clearable
          colon
          clickable
          required
        />
      </div>
      <van-field
        v-model="regsisterIfo.realName"
        label="真实姓名"
        maxlength="10"
        placeholder="请输入真实姓名"
        clearable
        colon
        clickable
        autofocus
        required
      />
      <!-- <van-field name="radio" label="单选框">
        <template #input>
          <van-radio-group v-model="regsisterIfo.gender" direction="horizontal">
            <van-radio name="1">男</van-radio>
            <van-radio name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>-->
      <van-field
        type="number"
        v-model="regsisterIfo.telPhone"
        label="手机号"
        placeholder="请输入手机号"
        clearable
        colon
        clickable
        required
      />
      <!-- <van-field
        type="email"
        v-model="regsisterIfo.email"
        label="邮箱"
        placeholder="请输入邮箱"
        clearable
        colon
        clickable
      />-->
      <div class="IDtype-box">
        <van-cell is-link title="证件类型" @click="showIdType = true" class="type-box" />
        <div class="IDtype">{{idTypeString}}</div>
      </div>
      <van-action-sheet
        v-model="showIdType"
        :actions="actions"
        @select="onSelect"
        cancel-text="取消"
      />
      <van-field
        type="text"
        v-model="regsisterIfo.idNumber"
        label="证件号"
        placeholder="请输入证件号"
        maxlength="18"
        clearable
        colon
        clickable
        required
      />
      <!-- <van-field
        readonly
        clickable
        :value="regsisterIfo.birthday"
        label="出生日期"
        placeholder="点击选择时间"
        @click="showDataPopup = true"
        colon
      />-->
    </div>
    <van-popup v-model="showDataPopup" position="bottom">
      <van-datetime-picker
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onConfim"
        @cancel="showDataPopup = false"
      />
    </van-popup>
    <div class="submit-btn">
      <van-button round block type="info" @click="toSubmit">提交</van-button>
    </div>
  </div>
</template>

<script>
import BackBar from "@/components/conten/backbar/BackBar";

import { Register, isRegister } from "network/register";
import { HeaderImg } from "network/uploadImg";
import { mapMutations } from "vuex";

import { isEmpty } from "common/utils";

import axios from "axios";

export default {
  name: "register",
  components: {
    BackBar,
  },
  data() {
    return {
      regsisterIfo: {
        userName: "",
        password: "",
        header: "",
        realName: "",
        nickName: "",
        idType: "1",
        idNumber: "",
        telPhone: "",
        email: "",
        gender: "3",
        birthday: "",
      },
      showIdType: false,
      checkPassword: "", //核对密码
      actions: [
        //证件类型选择部分
        { name: "大陆身份证" },
        { name: "护照" },
        { name: "港澳身份证" },
      ],
      idTypeString: "大陆身份证",
      minDate: new Date(1960, 0, 1), //日期选择部分
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      showDataPopup: false, //日期弹出判断
      uploader: [],
      fileList: [],
      isCanSubmit: false,
    };
  },
  methods: {
    ...mapMutations({
      isBackToTrue: "moduleUser/isBackToTrue",
    }),
    //回到登录页面
    toBack() {
      this.isBackToTrue();
      this.$router.push("/login");
    },
    //上传文件
    afterRead(file) {
      this.isCanSubmit = true;
      file.status = "uploading";
      file.message = "上传中...";
      // 大于1MB的图片都缩小像素上传
      if (file.file.size > 1048576) {
        let canvas = document.createElement("canvas"); // 创建Canvas对象(画布)
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content; // 指定图片的DataURL(图片的base64编码数据)
        img.onload = () => {
          canvas.width = 400;
          canvas.height = 300;
          context.drawImage(img, 0, 0, 400, 300);
          file.content = canvas.toDataURL(file.file.type, 0.92); // 0.92为默认压缩质量
          let files = this.dataURLtoFile(file.content, file.file.name);
          const data = new FormData();
          data.append("files", files);
          HeaderImg(data)
            .then((res) => {
              console.log("123", res);
              if (res.code == 200) {
                this.isCanSubmit = false;
                this.regsisterIfo.header = res.data[0];
                file.status = "";
                file.message = "";
              }
            })
            .catch(() => {
              this.isCanSubmit = false;
              this.$toast({
                message: "上传失败",
                position: "bottom",
              });
              file.status = "failed";
              file.message = "上传失败";
            });
        };
      } else {
        //小于1M直接上传
        const data = new FormData();
        data.append("files", file.file);
        HeaderImg(data)
          .then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.isCanSubmit = false;
              this.regsisterIfo.header = res.data[0];
              file.status = "";
              file.message = "";
            }
          })
          .catch((err) => {
            console.log(err);
            this.isCanSubmit = false;
            this.$toast({
              message: "上传失败",
              position: "bottom",
            });
            file.status = "failed";
            file.message = "上传失败";
          });
      }

      // const formdata = new FormData();
      // formdata.append("files", file.file);
      // // 此时可以自行将文件上传至服务器
      // HeaderImg(formdata).then((res) => {
      //   this.regsisterIfo.header = res.data[0];
      // });
    },
    //限制图片上传大小
    onOversize(file) {
      this.$toast({
        message:"图片不能超过500kb~",
        position:"bottom"
      })
    },
    //选择证件类型
    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.showIdType = false;
      // Toast(item.name);
      this.idTypeString = item.name;
    },

    //点击提交
    toSubmit() {
      //判断是否能够登陆
      if (this.isCanSubmit) {
        this.$toast({
          message: "图片正在上传中~",
          position: "bottom",
        });
        return;
      }
      let {
        userName,
        password,
        idNumber,
        realName,
        telPhone,
      } = this.regsisterIfo;
      if (isEmpty(password)) {
        this.$toast({
          message: "密码不能为空!~",
          position: "bottom",
        });
        return;
      } else if (password != this.checkPassword) {
        this.$toast({
          message: "两次密码输入不同~!",
          position: "bottom",
        });
        return;
      } else if (isEmpty(userName)) {
        this.$toast({
          message: "用户名不能为空~",
          position: "bottom",
        });
        return;
      } else if (isEmpty(realName)) {
        this.$toast({
          message: "真实姓名不能为空~",
          position: "bottom",
        });
        return;
      } else if (isEmpty(telPhone)) {
        this.$toast({
          message: "电话号码不能为空~",
          position: "bottom",
        });
        return;
      } else if (isEmpty(idNumber)) {
        this.$toast({
          message: "证件号不能为空~",
          position: "bottom",
        });
        return;
      } else {
        if (!/^1[3456789]\d{9}$/.test(telPhone)) {
          this.$toast({
            message: "电话号码格式不正确~",
            position: "bottom",
          });
          return;
        } else if (
          !/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            idNumber
          )
        ) {
          this.$toast({
            message: "证件号格式不正确~",
            position: "bottom",
          });
          return;
        }
      }
      isRegister({ userName }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          //在这里发送网络请求
          Register(this.regsisterIfo).then((res) => {
            if (res.code == 200) {
              this.$toast({
                message: "注册成功",
                position: "bottom",
              });
              this.isBackToTrue();
              this.$router.replace("/login");
            } else {
              this.$toast({
                message: "注册失败",
                position: "bottom",
              });
            }
          });
        } else {
          this.$toast({
            message: "用户名已存在",
            position: "bottom",
          });
        }
      });
    },

    //确认时间
    onConfim(time) {
      this.regsisterIfo.birthday = new Date(time).toLocaleDateString();
      this.showDataPopup = false;
    },
  },
};
</script>

<style scoped>
.register-content {
  padding-top: 50px;
}
.registerInfo-box {
  margin: 20px 10px 0;
}
.van-field {
  border-bottom: 1px solid #ccc;
  font-size: 14px;
  height: 45px;
}
.van-uploader {
  border-radius: 80px;
  /* overflow: hidden; */
}
.headimg-box {
  height: 90px;
}
.van-button {
  background: #ff5654;
  border: none;
}
.filebtn {
  height: 28px;
}
.submit-btn .van-button {
  width: 350px;
  margin: 25px auto;
}
.van-cell {
  font-size: 14px;
  border-bottom: 1px solid #ccc;
}
.IDtype-box {
  position: relative;
}
.IDtype-box div {
  font-size: 14px;
}
.IDtype {
  position: absolute;
  top: 12.5px;
  left: 112px;
  z-index: 999;
}
.van-popup {
  border-radius: 20px 20px 0 0;
}
</style>